package com.itheima.controller;

import com.itheima.entity.Address;
import com.itheima.entity.PageBean;
import com.itheima.entity.ResultInfo;
import com.itheima.entity.User;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 查询当前用户所有地址
     * @param params 封装所有的查询条件，包含：uid,current,size等
     */
    @RequestMapping("/find")
    public ResultInfo findAll(@RequestBody Map<String,Object> params, HttpSession session) {
        System.out.println("查询条件：" + params);
        //从map中获取查询条件
        int current = (int) params.get("current");
        int size = (int) params.get("size");
        //uid从会话域中获取
        User user = (User) session.getAttribute("user");
        int uid = user.getUid();
        //调用业务层
        PageBean<Address> pageBean = addressService.findAddress(current, size, params, uid);
        //封装成查询结果返回
        return new ResultInfo(true, "查询成功",pageBean);
    }

    @RequestMapping("/save")
    public ResultInfo saveAddress(@RequestBody Address address, HttpSession session) {
        System.out.println("地址信息：" + address);
        //uid要从会话域中获取
        User user = (User) session.getAttribute("user");
        //设置uid的值
        address.setUid(user.getUid());
        addressService.save(address);
        return new ResultInfo(true, "添加收货地址成功");
    }

    /**
     * 修改地址
     */
    @RequestMapping("/update")
    public ResultInfo updateAddress(@RequestBody Address address) {
        addressService.update(address);
        return new ResultInfo(true, "更新收货地址成功");
    }

    /**
     * 修改默认地址
     */
    @RequestMapping("/changeDefault")
    public ResultInfo changeDefaultAddress(Integer aid, HttpSession session) {
        User user = (User) session.getAttribute("user");
        int uid = user.getUid();
        addressService.changeDefaultAddress(uid,aid);
        return new ResultInfo(true, "修改默认收货地址成功");
    }

    /**
     * 删除一条收货地址
     */
    @RequestMapping("/delete")
    public ResultInfo deleteAddress(Integer aid) {
        addressService.delete(aid);
        return new ResultInfo(true, "成功删除收货地址");
    }
}
